package com.engine.update.cmd;

import com.engine.core.domain.GenTable;
import com.engine.core.domain.GenTableColumn;
import com.engine.core.gen.Mysql;
import com.engine.core.interceptor.JdbcCommandContext;
import com.engine.core.rowMapper.JdbcTypeBiz;
import com.engine.core.rowMapper.MappedType;
import com.engine.core.util.JdbcTemplateUtils;
import com.engine.core.util.QueryUtil;
import com.engine.core.util.Response;
import com.engine.core.util.Utils;
import com.engine.core.interceptor.ResponseCommand;
import com.engine.system.User;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

public class DeleteOneCommand extends ResponseCommand {
    /**
     * @param commandContext
     * @return
     * @throws Exception
     */
    @Override
    public Response execute(JdbcCommandContext commandContext) throws Exception {
        Response response=Response.static_success("执行成功!");
        String tableName=(String)params.get(QueryUtil.QUERY_TABLE);
        JdbcTemplate jdbcTemplate=commandContext.getJdbcTemplate();
        GenTable genTable= Mysql.getTable(tableName,jdbcTemplate);
        String ids=(String)params.get(QueryUtil.QUERY_ID);
        Map<String,String> othersMap= JdbcTypeBiz.getUpdateOthersByParams(params);

        GenTableColumn genTableColumn=genTable.getPkColumn();

        MappedType pkMappedType=new MappedType(Mysql.javaTypeByColumnType(genTableColumn.getColumnType()),
                genTableColumn.getColumnName(),
                genTableColumn);

        Object objs=null;
        try {
            objs=Utils.convertValueOrList(ids,pkMappedType.getTypeName());
        } catch (Exception e) {
            response.setErr(e);
            return response;
        }
        LinkedHashMap<String,MappedType> columnsTypeMap=new LinkedHashMap<String,MappedType>();
        columnsTypeMap.put(genTableColumn.getColumnName(),pkMappedType);
        try {
            response=JdbcTemplateUtils.deleteOneDataById(genTable,jdbcTemplate,objs,columnsTypeMap,othersMap);
        } catch (Exception e) {
            response.setErr(e);
        }
        return response;
    }

    public DeleteOneCommand(User user, Map<String, Object> params) {
        super(user, params);
    }
}
